<?php

require_once("Site.class.php");
require_once("Hotnews.class.php");

class HotnewsManager {

    private $connection;

    const SAVE_HN_QUERY = "INSERT INTO hotnews (title, abstract, content, image, visible, order) VALUES (:title, :abstract, :content, :image, :visible, :order);";
    const UPDATE_HN_QUERY = "UPDATE hotnews SET title = :title, abstract = :abstract, content = :content, image = :image, visible = :visible, order = :order WHERE id = :id;";
    const GET_HN_QUERY = "SELECT * FROM hotnews WHERE visible = 1 ORDER BY hotnews.order ASC;";

    public function __construct() {
        $this->connection = new PDO(
                        "mysql:host=" . Site::DB_HOST . ";dbname=" . Site::DB_NAME,
                        Site::DB_USERNAME,
                        Site::DB_PASSWORD,
                        array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
        );
    }

    public function save_hotnews(&$hn) {
        $statement = $this->connection->prepare(self::SAVE_HN_QUERY);
        $statement->execute(array(
            'title' => $hn->title,
            'abstract' => $hn->abstract,
            'content' => $hn->content,
            'image' => $hn->image,
            'visible' => $hn->visible,
            'order' => $hn->order
        ));
        if ($statement->rowCount() <= 0)
            throw new Exception();
        $hn->id = $this->connection->lastInsertId();
    }

    public function update_hotnews($hn) {
        $statement = $this->connection->prepare(self::UPDATE_HN_QUERY);
        $statement->execute(array(
            'id' => $hn->id,
            'title' => $hn->title,
            'abstract' => $hn->abstract,
            'content' => $hn->content,
            'image' => $hn->image,
            'visible' => $hn->visible,
            'order' => $hn->order
        ));
        if ($statement->rowCount() <= 0)
            throw new Exception();
    }

    public function get_visible_hotnews() {
        $statement = $this->connection->prepare(self::GET_HN_QUERY);
        $statement->execute();
        $result = array();
        $h = null;
        while ($hn = $statement->fetch(PDO::FETCH_ASSOC)) {
            $h = new Hotnews();
            foreach ($hn as $key => $value) {
                $h->{$key} = $value;
            }

            array_push($result, $h);
        }
        return $result;
    }

}

?>